<!--
 * @Author: your name
 * @Date: 2021-01-10 12:55:48
 * @LastEditTime: 2021-01-14 15:20:55
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \shopping\src\pages\pay\main.vue
-->
<template>
  <view class="container">
    <view class="address">
      <view class="address_info" v-if="address.userName">
        <view class="detail_address"
          ><text user-select>{{ detailAddress }}</text></view
        >
        <view class="user_info">
          <text class="username">{{ address.userName }}</text>
          <text class="telNumber">{{ address.telNumber }}</text>
          <text class="iconfont icon-fankui" @tap="getAddressHandle"></text>
        </view>
      </view>
      <!-- 地址为空 -->
      <view class="address_empty" @tap="getAddressHandle" v-else>
        <view class="getAddress"> 选择地址 </view>
      </view>
    </view>
    <view class="selected_goods">
      <view class="title">已选商品</view>
      <block v-for="item in cartList" :key="item.goods_id">
        <GoodsItem v-if="item.goods_selected" :item="item">
          <view class="count">x{{ item.goods_count }}</view>
        </GoodsItem>
      </block>
    </view>

    <!-- 底部栏 -->
    <view class="bottom">
      <text>合计：</text>
      <text class="price">{{ priceCount }}</text>
      <text class="close_btn" @tap="payHandle">支付({{ account }})</text>
    </view>
  </view>
</template>

<script>
import GoodsItem from "@/components/goodsItem";
import { createOrder, getPayParams, checkOrder } from "@/api/index.js";

export default {
  components: {
    GoodsItem,
  },
  onLoad() {
    this.address = uni.getStorageSync("address") || {};
    this.cartList = uni.getStorageSync("cartList") || [];
  },
  data() {
    return {
      address: {},
      cartList: [],
    };
  },
  computed: {
    detailAddress() {
      const { provinceName, cityName, countyName, detailInfo } = this.address;
      return provinceName + cityName + countyName + detailInfo;
    },
    account() {
      let account = 0;
      this.cartList.map((item) => {
        if (item.goods_selected) {
          account += item.goods_count;
        }
      });
      return account;
    },
    priceCount() {
      let priceCount = 0;
      this.cartList.map((item) => {
        if (item.goods_selected) {
          priceCount += item.goods_count * item.goods_price;
        }
      });
      return priceCount;
    },
  },
  methods: {
    // 获取用户收货地址
    getAddressHandle() {
      uni.chooseAddress({
        success: (res) => {
          // console.log(res);
          this.address = res;
          // 保存到本地存储
          uni.setStorageSync("address", res);
        },
      });
    },
    async payHandle() {
      console.log("微信支付流程开始");

      if (!this.address.userName) {
        uni.showToast({
          title: "收货地址未填写！",
          icon: "none",
          duration: 1000,
        });
        return;
      }

      if (!this.cartList.length) {
        uni.showToast({
          title: "请先去商城看看!",
          icon: "none",
          duration: 1000,
        });
        return;
      }

      // 1.筛选已选的商品，并将数据格式转换为api需要的格式
      const goods = this.cartList
        .filter((item) => item.goods_selected)
        .map((item) => {
          return {
            goods_id: item.goods_id,
            goods_number: item.goods_count,
            goods_price: item.goods_price,
          };
        });
      // console.log(goods, "商品");
      try {
        // 支付流程1.创建订单，返回订单号
        const { order_number } = (
          await createOrder({
            goods,
            order_price: this.priceCount,
            consignee_addr: this.detailAddress,
          })
        ).data.message;

        // console.log(order_number, "创建订单");

        // 支付流程2.调用支付接口，返回微信支付需要的参数
        const { pay } = (await getPayParams({ order_number })).data.message;
        console.log(pay, "支付参数");
        // 支付流程3.调用微信支付接口，完成支付
        await wx.requestPayment(pay);

        // 支付流程4.支付结束，后端需要掉接口检查订单的支付状态
        await checkOrder({ order_number });
        // 给用户一个支付成功的提示
        uni.showToast({
          title: "支付成功",
          duration: 1000,
        });

        // 支付成功后，跳转页面，清理本地存储购物车数据
        const cartList = cartList.filter((item) => !item.goods_selected);
        uni.setStorageSync("cartList", cartList);
        // 跳转到订单页面 - redirectTo 相当于 Vue 的 replace 替换页面
        uni.redirectTo({
          url: "/pages/order/main",
        });
        // console.log(cartList);
      } catch (error) {
        uni.showToast({
          title: "支付失败",
          icon: "none",
          duration: 1000,
        });
      }
    },
  },
};
</script>

<style lang="less" scoped>
.container {
  background-color: #f9f9f9;
  padding: 0 20rpx;
  padding-bottom: 83rpx;
}
.address {
  display: flex;
  align-items: center;

  height: 187rpx;
  width: 710rpx;
  background-color: #fff;
  margin: 20rpx 0;
  .address_info {
    padding: 0 20rpx;
    .detail_address {
      font-size: 40rpx;
      // font-family: "PingFangSC-Medium";
      font-weight: 700;
    }
    .user_info {
      display: flex;
      margin-top: 18rpx;
      text {
        font-size: 36rpx;
        color: #434343;
      }
      .telNumber {
        flex: 1;
      }
      .username {
        margin-right: 30rpx;
      }
    }
  }

  .address_empty {
    width: 300rpx;
    height: 90rpx;
    margin: auto;
    border-radius: 45rpx;
    border: 2rpx solid var(--mainColor);
    color: var(--mainColor);
    line-height: 90rpx;
    text-align: center;
    font-size: 35rpx;
  }
}
.selected_goods {
  background-color: #fff;
  .title {
    padding: 17rpx 26rpx;
    font-size: 26rpx;
    font-weight: 700;
  }
  .count {
    position: absolute;
    right: 0;
    bottom: 0;
    font-size: 28rpx;
  }
}
.bottom {
  position: fixed;
  bottom: 0;
  width: 750rpx;
  height: 83rpx;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  background-color: #fff;
  padding: 0 20rpx;
  .price {
    flex: 1;
  }
  .close_btn {
    background-color: var(--mainColor);
    width: 150rpx;
    height: 52rpx;
    border-radius: 26rpx;
    color: #fff;
    line-height: 52rpx;
    text-align: center;
    margin-right: 20rpx;
  }
}
</style>